<?php
namespace Wanecho\Mobilelogin\Api\Controllers;

use Flarum\Settings\SettingsRepositoryInterface;
use Psr\Http\Message\ServerRequestInterface;
use Wanecho\Mobilelogin\Api\Libraries\SMS;
use Illuminate\Support\Arr;
use Laminas\Diactoros\Response\JsonResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Wanecho\Mobilelogin\Api\WanechoSms;
use Carbon\Carbon;
use Flarum\Http\RequestUtil;


class SendCodeController implements RequestHandlerInterface
{
    // public $serializer = SendCodeSerializer::class;
    protected $settings;


    public function __construct(SettingsRepositoryInterface $settings)
    {
        $this->settings = $settings;
    }
    
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        // $body = $request->getParsedBody();
        $body = $request->getParsedBody();
        $phone = Arr::get($body, 'phone');
        if ($phone == '') {
            return new JsonResponse('请输入手机号码', 500);
        }
        if(!preg_match("/^1[3457689]\d{9}$/", $phone)){
            return new JsonResponse('手机号码错误', 500);
        }

        $actor = RequestUtil::getActor($request);
        
        $code = random_int(100000, 999999);
        // print_r($this->settings);
        // return new JsonResponse('验证码发送失败', 500);
        $SMS = new SMS($this->settings);
        try {
            // $res = true;
            $res = $SMS->sendSMS(
                $phone,
                $this->settings->get('mobilelogin.TemplateCode'),
                $params = [
                    'code' => $code
                ],
                $this->settings->get('mobilelogin.SignName')
            );
        } catch (\Throwable $th) {
            return new JsonResponse($th->getMessage(), 500);
        }

        if ($res === false) {
            return new JsonResponse('验证码发送失败', 500);
        }
        

        $created_at = Carbon::now();
        // 记录到表，后续用于校验
        WanechoSms::create([
            'mobile' => $phone,
            'user_id' => $actor->id,
            'code' => $code,
            'is_active' => 0,
            'created_at' => $created_at
        ]);
        // throw new Exception('Invalid state');
        return new JsonResponse('验证码已发送', 200);

    }

}